const Mock = require('mockjs');
const jsonServer = require('json-server')
const axios  = require('axios');
const JWT = require('jsonwebtoken')
const server = jsonServer.create()
const {swiper, list} =Mock.mock({
  "swiper|4": [
    "@image(100x100,@color)"
  ],
  "list|40": [
    {
      "id|+1": 1,
      "image": "@image(100x100,@color)",
      "title": "@ctitle(6,10)",
      "price|1-20": 1
    }
  ]
})
const router = jsonServer.router({swiper, list})
const middlewares = jsonServer.defaults()
let cars = [];
let users = [];
// avatarUrl
// nickName
// openid

let addressList = [];
// id
// username
// tel
// address
// isDefault
// addressCode

server.use(jsonServer.bodyParser)
server.use(middlewares)
// 获取购物车
server.get('/api/getCar',(req,res) => {
  res.send({
    code: 200,
    cars
  })
})

// 加购
server.get('/api/addCar',(req,res) => {
  const {id} = req.query;
  // 1. 判断购物车是否有当前商品
  const carItem = cars.find(item => item.id == id);
  if(carItem) {
    // 2. 有当前商品，数量+1
    carItem.count +=1
  } else {
    // 3. 没有，unshift添加当前商品，count默认为1
    const item = list.find(item => item.id == id);
    cars.unshift({
      ...item,
      count: 1
    })
  }
  res.send({
    code: 200
  })
})
// 数量+
server.get('/api/addCount', (req,res) => {
  const {id} = req.query;
  // 对匹配到的购物车数据进行数量+1
  cars.forEach(item => {
    if(item.id == id) {
      item.count++
    }
  })
  res.send({
    code: 200,
    cars
  })
})
// 数量-
server.get('/api/subCount', (req,res) => {
  const {id} = req.query;
  // 对匹配到的购物车数据进行数量-1
  cars.forEach(item => {
    if(item.id == id) {
      item.count--
    }
  })
  res.send({
    code: 200,
    cars
  })
})
// 删除购物车
server.get('/api/deleteItem', (req,res) => {
  const {id} = req.query;
  // 对匹配到id进行过滤删除
  cars = cars.filter(item => item.id != id)
  res.send({
    code: 200,
    cars
  })
})
// 勾选单个
server.post('/api/checkItem',(req,res) => {
  const {id, checked} = req.body;
  // 将勾选的当条数据checked字段进行修改
  cars.forEach(item => {
    if(item.id == id) {
      item.checked = checked;
    }
  })
  res.send({
    code: 200,
    cars
  })
})
// 全选
server.post('/api/checkAll',(req,res) => {
  const {checked} = req.body;
  // 将每条数据checked字段进行修改
  cars.forEach(item => {
    item.checked = checked
  })
  res.send({
    code: 200,
    cars
  })
})

// 本地登陆服务，换取openid
server.post('/api/login',(req,res) => {
  const {code} = req.body;
  // 微信开放接口，通过code换取openid
  axios.get('https://api.weixin.qq.com/sns/jscode2session',{
    params: {
      appid:'wx63a2ab5688e50b12',
      // app密钥
      secret:'755702315b8c73dfd2d0ce853930706a',
      js_code: code,
      grant_type:'authorization_code'
    }
  }).then(result => {
    const {openid} = result.data;
    // 生成token返回
    const token = JWT.sign({
      openid
    }, '666')
    const user = users.find(item => item.openid === openid)
    res.send({
      code: 200,
      token,
      user: user ? {
        avatarUrl: user.avatarUrl,
        nickName: user.nickName
      } : null
    })
  })
})

server.post('/api/register',(req,res) => {
  const {avatarUrl, nickName} = req.body;
  const {token} = req.headers;
  // 解析token，获取openid，user表注册
  JWT.verify(token,'666',(err, decoded) => {
    console.log(decoded,'decoded')
    users.push({
      openid: decoded.openid,
      avatarUrl,
      nickName
    })
    res.send({
      code: 200,
      avatarUrl,
      nickName
    })
  })
  console.log(avatarUrl, nickName,token)
})
// 创建/编辑地址，根据id去判断场景
server.post('/api/createOrUpdateAddress', (req,res) => {
  const {id, username, tel, address, addressCode, isDefault} = req.body;
  if(id) {
    addressList = addressList.map((item, index) => {
      if(item.id == id) {
        return {id, username, tel, address, addressCode, isDefault}
      }
      return {
        ...item,
        // 如果传入是isDefault为true,为保证最多有一条默认地址，将其他强制改为false
        isDefault: isDefault ? false : item.isDefault
      }
    })
  } else {
    addressList.unshift({
      id: new Date().getTime(),
      username, 
      tel, 
      address, 
      addressCode, 
      isDefault
    })
  }
  res.send({
    code: 200
  })
})

server.get('/api/getAddres',(req,res) => {
  res.send({
    code: 200,
    addressList
  })
})

server.get('/api/getAddressItem',(req,res) => {
  res.send({
    code: 200,
    data: addressList.find(item => item.id == req.query.id)
  })
})

server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})